package juc;

import java.util.LinkedList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁TryLock方法练习
 */
public class ReentrantLockTryLockTest implements Runnable {
    //初始话锁
    private static Lock locks = new ReentrantLock();


    @Override
    public void run() {
        try {
            //尝试获取锁成功
            if (locks.tryLock()) {
                System.out.println("当前线程=" + Thread.currentThread().getName() + "获取锁成功");
//                Thread.sleep(3000);//睡眠两秒钟
            } else {//尝试获取锁失败
                System.out.println("当前线程=" + Thread.currentThread().getName() + "获取锁失败");
            }
        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
        } finally {//最后释放锁
            try {
                locks.unlock();
                System.out.println("当前线程=" + Thread.currentThread().getName() + "释放锁成功");
            } catch (Exception e) {
                System.out.println("当前线程=" + Thread.currentThread().getName() + "释放锁失败");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReentrantLockTryLockTest test = new ReentrantLockTryLockTest();
        Thread t1 = new Thread(test);
        Thread t2 = new Thread(test);
        Thread t3 = new Thread(test);
        t1.start();
        t2.start();
        t3.start();
        // join()线程顺序执行(结束的时候)
        t1.join();
        t2.join();
        t3.join();
        System.out.println("over");


    }
}
